package com.lx.handler;

import com.lx.entity.User;
import com.lx.executor.UserExecutor;
import com.lx.stereotype.Handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import java.util.Optional;

import reactor.core.publisher.Mono;

/**
 * 用户接口
 *
 * @author 段誉
 * @create 2019-05-15 15:10
 */
@Handler
public class UserHandler {
  @Autowired
  private UserExecutor userExecutor;

  /**
   * @desc 查询所有用户
   * @Author 段誉
   * @Date 2019/5/15 16:59
   * @method
   */
  public Mono<ServerResponse> getAll(ServerRequest serverRequest) {
    return userExecutor.getAll();
  }

  /**
   * @desc 添加用户
   * put请求需要传json格式的数据才能接受到，
   * 如果没有接收到数据不会执行userExecutor.add(user)方法，也没有返回值（还在找怎么解决）
   * @Author 段誉
   * @Date 2019/5/15 17:00
   * @method
   */
  public Mono<ServerResponse> add(ServerRequest serverRequest) {
    return serverRequest.bodyToMono(User.class)
            .flatMap(user -> userExecutor.add(user));
  }

  /**
   * @desc 根据用户名进行模糊查询
   * @Author 段誉
   * @Date 2019/5/20 14:09
   * @method
   */
  public Mono<ServerResponse> getListByName(ServerRequest serverRequest) {
//    serverRequest.pathVariable("name");
//    获取路径上的值比如/user/list/{name}
    //获取url后边的参数
    Optional<String> name = serverRequest.queryParam("name");
    return userExecutor.getListByName(name.isPresent() ? name.get() : "");
  }


  /**
   * @desc 根据名字进行模糊分页查询
   * @Author 段誉
   * @Date 2019/5/20 15:15
   * @method
   */
  public Mono<ServerResponse> getListPageByName(ServerRequest serverRequest) {
    Optional<String> nameO = serverRequest.queryParam("name");
    Optional<String> pageNumO = serverRequest.queryParam("pageNum");
    Optional<String> pageSizeO = serverRequest.queryParam("pageSize");
    String name = nameO.isPresent() ? nameO.get() : "";
//    jpa分页的页码是从0开始的
    Integer pageNum = pageNumO.isPresent() ? Integer.valueOf(pageNumO.get()) : 0;
    Integer pageSize = pageSizeO.isPresent() ? Integer.valueOf(pageSizeO.get()) : 10;
    return userExecutor.getListPageByName(name, pageNum, pageSize);
  }
}
